"""
Set the wallpaper as the picture got from national geographic picture of the day
by xpwang@bea.com
FIXME: Needs to set the registry to keep the wallpaper setting after restart system
"""
import ctypes
import Image
import calendar
import urllib
import socket
import os
import time

STOREDIR = 'C:/lg_wallpaper/pod/'
DOWNLOADED = 0

def setWallpaperFromBMP(imagepath):
    SPI_SETDESKWALLPAPER = 20 # According to http://support.microsoft.com/default.aspx?scid=97142
    ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, imagepath , 0) #SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE

def setWallPaper(imagePath):
    """Given a path to an image, convert it to bmp and set it as wallpaper"""
    bmpImage = Image.open(imagePath)
    newPath = STOREDIR + 'mywallpaper.bmp'
    bmpImage.save(newPath, "BMP")
    setWallpaperFromBMP(newPath)
    
def getPicture():
    try:
        sock = urllib.urlopen("http://lava.nationalgeographic.com/cgi-bin/pod/PhotoOfTheDay.cgi")
        htmlSource = sock.read()
        sock.close()    
        pos1 = htmlSource.find('Enlarge</a>')
        pos2 = htmlSource.find('Wallpaper</a>')
        page2 = htmlSource[pos1+50:pos2-2]
        pageurl = 'http://photography.nationalgeographic.com'+page2
        print pageurl
        
        sock = urllib.urlopen(pageurl)
        htmlSource = sock.read()
        sock.close()    
        pos1 = htmlSource.find('art-icon-wallpaper-1280.gif')
        pos2 = htmlSource.find('1280 x 1024 pixels')
        filename = htmlSource[pos1+42:pos2-2]
        print filename
        fileurl = 'http://photography.nationalgeographic.com'+filename
        onlyfile = filename[filename.rfind("/")+1:];
        print onlyfile
        fname = STOREDIR + onlyfile
        if not os.path.exists(fname):
            print 'file not retrieved'
            urllib.urlretrieve(fileurl, fname)
            print 'got the picture from ' + fileurl
        else:
            print 'The file is retrieved'
        return fname
    except Error:
        print "fail to getting picture of ",yy,mm,dd
        pass
    
    return fname

def getPicture2():
    now = time.localtime(time.time())
    year, month, day, hour, minute, second, weekday, yearday, daylight = now
    print "%04d-%02d-%02d" % (year, month, day)
    #print "%02d:%02d:%02d" % (hour, minute, second)
    #print ("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")[weekday], yearday
    return getPictureByDate(year, month, day)

def getPictureByDate(yy,mm,dd):
    yy = ""+str(yy)
    yy = yy[-2:]
    mm = "0"+str(mm)
    mm = mm[-2:]
    dd = "0"+str(dd)
    dd = dd[-2:]
    
    print 'getting the picture of ',yy,mm,dd
    
    try:
        pageurl = 'http://lava.nationalgeographic.com/cgi-bin/pod/wallpaper.cgi?day='+str(dd)+'&month='+str(mm)+'&year='+str(yy)
        print pageurl
        sock = urllib.urlopen(pageurl)
        htmlSource = sock.read()
        sock.close()    
        pos1 = htmlSource.find('art-icon-wallpaper-1280.gif')
        pos2 = htmlSource.find('1280 x 1024 pixels')
        filename = htmlSource[pos1+42:pos2-2]
        print filename
        fileurl = 'http://photography.nationalgeographic.com'+filename
        onlyfile = filename[filename.rfind("/")+1:];
        print onlyfile
        fname = STOREDIR + onlyfile
        if not os.path.exists(fname):
            print 'file not retrieved'
            urllib.urlretrieve(fileurl, fname)
            print 'got the picture from ' + fileurl
        else:
            print 'The file is retrieved'
        return fname
    except Error:
        print "fail to getting picture of ",yy,mm,dd
        pass
    
def setWallpaperOfToday():
    #filename  = getPicture()
    filename  = getPicture()
    print 'the filename is ' + filename
    setWallPaper(filename)

def setWallpaperByDate(yy,mm,dd):
    filename  = getPictureByDate(yy,mm,dd)
    setWallPaper(filename)

def prepare():
    #prepare the directory
    if not os.path.exists(STOREDIR):
        print 'going to make dir ' + STOREDIR
        os.makedirs(STOREDIR)
    print 'prepare done ...'

def getAllPictures():
    y=7
    for m in range(1,13):
        for d in range(1,32):
            getPictureByDate(y,m,d)

            
prepare()
setWallpaperOfToday()

#setWallpaperByDate(6,10,11)
#getAllPictures()
print 'Wallpaper set ok!'
